function showDueData(){
    const afterDueDateBox=document.getElementById('afterDueDate');
    let insIdPage;
    if(insRole==='ins'){
        insIdPage=insId;
    }else{
        //特殊，陆的情况
        if(insRole==='admin'){
            if(insId==='LZADM002' || insId==='LZADM001'){
                insIdPage='LZINS001';
            }
            
        }
    }
    // console.log('ins id page:',insIdPage);

    afterDueDateBox.innerHTML='';
    fetch('/get_after_duedate_data')
    .then(response=>response.json())
    .then(data=>{
        // console.log('due data:',data['data']);       
        
        if(data['res']==='ok'){
            
            let count=0;
            const dueData=data['data']['due_data'];
            let cusStr='';
            dueData.forEach(item=>{   
                if(item['ins_ids'].includes(insIdPage)){
                    if(item['cls_type']==='常规课程'){
                        if(item['days_diff']>=1 && item['days_diff']<=30){
                            cusStr+=`<span style="color:#b55bb1;">${item['cus_name']}（-${item['days_diff']}天），</span>`;
                            count+=1;
                        }   
                    }
                    if(item['cls_type']==='限时课程'){
                        if(item['days_diff']>=1 && item['days_diff']<=30){
                            cusStr+=`<span style="color:#b55bb1;">${item['cus_name']}(-${item['days_diff']}天)，</span>`;
                            count+=1;
                        }   
                    }
                                     
                }                      
            });
            cusStr=cusStr.slice(0,-8)+'</span>';
            const hr=document.createElement('hr');
            const div=document.createElement('div');
            div.style.fontSize='12px';
            div.style.textAlign='center';
            div.innerHTML=`<div style="background-color:#b55bb1;color:#ffffff">请关注以下会员的续课情况</div><p style="color:#b55bb1;">${cusStr}</p>`;

            // thisMonthDueCusList.appendChild(hr);
            afterDueDateBox.appendChild(div);

            if(count===0){
                afterDueDateBox.innerHTML='';
            }


        }else{
            afterDueDateBox.innerHTML='';
        }

    })
    .catch(error=>console.log(error));
}

function show9Point9ClsInfo(){
    const nineYuanClsInfo=document.getElementById('nineYuanClsInfo');
    let insIdPage;
    if(insRole==='ins'){
        insIdPage=insId;
    }else{
        //特殊，陆的情况
        // if(insRole==='admin'){
        //     if(insId==='LZADM002' || insId==='LZADM001'){
        //         insIdPage='LZINS001';
        //     }
            
        // }
        insIdPage='LZINS001';
    }
    // console.log('ins id page:',insIdPage);

    nineYuanClsInfo.innerHTML='';
    fetch('/get_9_point_9_yuan_cls')
    .then(response=>response.json())
    .then(data=>{
        // console.log('9.9yuan data:',data['data']);       
        
        if(data['res']==='ok'){
           const nineYuanData=data['data'];
           if(nineYuanData.length>0){
                

                let nineYuanList=[]
                nineYuanData.forEach(item=>{
                    if(item[10].includes(insIdPage)){
                        nineYuanList.push(item);
                    }
                });

                const today=new Date();
                today.setHours(0,0,0,0);
                let nineYuanStr=''; 
                let n=0;
                nineYuanList.forEach(item=>{
                    if(item[10].includes(insIdPage)){
                        const endDate=new Date(item[8]);
                        endDate.setDate(endDate.getDate()-1);
                        if(n===0){
                            if(endDate===today){
                                nineYuanStr+=`<span style='color:red;'>${item[1]}（${endDate.getMonth()+1}.${endDate.getDate()}）</span>`;
                            }else{
                                nineYuanStr+=`<span style='color:#4e70b5;'>${item[1]}（${endDate.getMonth()+1}.${endDate.getDate()}）</span>`;
                            }
                        }else{
                            if(endDate===today){
                                nineYuanStr+=`<span style='color:red;'>，${item[1]}（${endDate.getMonth()+1}.${endDate.getDate()}）</span>`;
                            }else{
                                nineYuanStr+=`<span style='color:#4e70b5;'>，${item[1]}（${endDate.getMonth()+1}.${endDate.getDate()}）</span>`;
                            }
                        }
                        n+=1;
                    }
                    
                    
                });
                // nineYuanStr=nineYuanStr.slice(1,);

                
                const div=document.createElement('div');
                div.style.fontSize='12px';
                div.style.textAlign='center';
                if(nineYuanStr!==''){
                    div.innerHTML=`<div style="background-color:#4e70b5;color:#ffffff">下列会员有9.9元优惠课程未上</div><p style="color:#cf432d;">${nineYuanStr}</p>`;
                    nineYuanClsInfo.appendChild(div);
                }else{
                    nineYuanClsInfo.innerHTML='';
                }
                
                

           }else{
                nineYuanClsInfo.innerHTML='';
           }

        }else{
            nineYuanClsInfo.innerHTML='';
        }

    })
    .catch(error=>console.log(error));
}


function indexMsgAlert(){
    const msgBox=document.getElementById('clsMsg');
    let insIdPage;
    if(insRole==='ins'){
        insIdPage=insId;
    }else{
        //特殊，陆的情况
        if(insRole==='admin'){
            if(insId==='LZADM002' || insId==='LZADM001'){
                insIdPage='LZINS001';
            }
            
        }
    }
    // console.log('ins id page:',insIdPage);

    msgBox.innerHTML='';
    fetch('./query_lmt_15')
    .then(response=>response.json())
    .then(data=>{
        // console.log('lmt 15 data:',data)
        if(data['res']==='ok'){
            msgBox.style.display='none';

            const table=document.createElement('table');
            const title=document.createElement('div');
            title.style.width='100%';     
            title.style.display='flex';
            title.style.justifyContent='center';
            title.style.alignContent='center';
            title.innerHTML=`<span style='color:#FFFFFF;background-color:#496191;padding-left:4px;padding-right:4px;'>新人首单30天15节限时包月上课情况</span>`;     
                
            const headrow=table.insertRow();
            headrow.classList.add('header-row');
            const headerOrder=['姓名','关联卡号','开始日期','结束日期','剩余节数']
            for(const colName of headerOrder){
                const cell=headrow.insertCell();
                cell.textContent=colName;
            }

            const dataIndexMap = {
                '姓名': 1,
                '关联卡号': 2,
                '开始日期': 5,
                '结束日期': 6,
                '剩余节数': 4
              };

            data['data'].forEach(item => {
                if(item[7].includes(insIdPage)){
                    // console.log(item[7],insIdPage);
                // const t=true;
                // if(t){                     
                    const row = table.insertRow();
                    for (const colName of headerOrder) {
                        const dataIndex = dataIndexMap[colName];
                        const cell = row.insertCell();
                        cell.innerHTML = `<span>${item[dataIndex]}</span>`;
                        if(colName==='开始日期'){
                            const showDate=dateToStringGmt(item[dataIndex],'date');
                            cell.innerHTML = `<span>${showDate}</span>`;
                        }
                        if(colName==='结束日期'){
                            let showDate=new Date(item[dataIndex]);
                            showDate.setDate(showDate.getDate()-1)
                            showDate=dateToStringGmt(showDate,'date');
                            cell.innerHTML = `<span>${showDate}</span>`;
                            // 检查剩余节数并设置结束日期单元格样式
                            if (item[4] <= 5) {
                                cell.innerHTML = `<span style='color:red;font-size:10px;'>${showDate}</span>`;
                            }
                            const today=new Date();
                            let calDate=new Date(item[dataIndex]);
                            calDate.setDate(calDate.getDate()-1)
                            const daysDiff=compareDatesOnly2(today,calDate);
                            if(daysDiff<=5){
                                cell.innerHTML = `<span style='color:red;font-size:8px;'>${showDate} (剩${daysDiff}天)</span>`;       
                                if(daysDiff===0){
                                    cell.innerHTML = `<span style='color:red;font-size:8px;'>${showDate} (今天)</span>`;     
                                }                   
                            }
                        }
                        if(colName==='剩余节数'){
                            if(item[dataIndex]<=5){
                                cell.innerHTML = `<span style='color:red;font-size:12px;'>${item[dataIndex]}</span>`;
                                // 设置结束日期单元格样式
                                const endDateCell = row.cells[headerOrder.indexOf('结束日期')];
                                endDateCell.innerHTML = `<span style='color:red;font-size:8px;'>${endDateCell.textContent}</span>`;
                            }
                            const today=new Date();
                            let showDate=new Date(item[6]);
                            showDate.setDate(showDate.getDate()-1)
                            const daysDiff=compareDatesOnly2(today,showDate);
                            if(daysDiff<=5){                         
                                showDate=dateToStringGmt(showDate,'date');
                                cell.innerHTML = `<span style='color:red;font-size:12px;'>${item[dataIndex]}</span>`;                    
                            }

                        }
                        if(colName==='关联卡号'){
                            cell.style.fontSize='8px';
                        }
                      }
                    row.classList.add('lmt-15-list');
                }
            });

            let showDiv = data['data'].some(item => item[7].includes(insIdPage));
            if(showDiv){
                msgBox.style.display='flex';
                msgBox.appendChild(title);
                const hr=document.createElement('hr');
                hr.style.width='100%';
                msgBox.appendChild(hr);
                msgBox.appendChild(table);
                msgBox.classList.add('lmt-15-msgbox');
            }else{
                msgBox.style.display='none';
            }
            




        }
    })
    .catch(error=>{
        console.log(error)
    });
}

function indexMsgAlertAll(insIdList,divId,divTitle){
    const msgBox=document.getElementById(divId);
    const titleBox=document.getElementById(divTitle);
   
    // console.log('ins id page:',insIdPage);

    msgBox.innerHTML='';
    fetch('./query_lmt_15')
    .then(response=>response.json())
    .then(data=>{
        // console.log('lmt 15 data:',data)
        if(data['res']==='ok'){
            msgBox.style.display='none';

            const table=document.createElement('table');
            const title=document.createElement('div');
            title.style.width='100%';     
            title.style.display='flex';
            title.style.justifyContent='center';
            title.style.alignContent='center';
            title.innerHTML=`<span style='color:#FFFFFF;background-color:#496191;padding-left:4px;padding-right:4px;'>会员30天15节限时包月上课情况</span>`;     
                
            const headrow=table.insertRow();
            headrow.classList.add('header-row');
            const headerOrder=['序号','姓名','关联卡号','开始日期','结束日期','剩余节数','返还金额','教练']
            for(const colName of headerOrder){
                const cell=headrow.insertCell();
                cell.textContent=colName;
            }

            const dataIndexMap = {
                '序号':'auto',
                '姓名': 1,
                '关联卡号': 2,
                '开始日期': 5,
                '结束日期': 6,
                '剩余节数': 4,
                '返还金额':9
              };

            let nOrder=1;
            insIdList.forEach(insIdName=>{
                const insId=insIdName.slice(0,8);                
                data['data'].forEach(item => {
                    const row = table.insertRow();                       
                    if(item[7].includes(insId)){                       // console.log(insId);                                             
                        for (const colName of headerOrder) {
                            const dataIndex = dataIndexMap[colName];
                            const cell = row.insertCell();
                            if(dataIndex==='auto'){
                                cell.innerHTML = `<span>${nOrder}</span>`;
                            }else{
                                cell.innerHTML = `<span>${item[dataIndex]}</span>`;
                                if(colName==='开始日期'){
                                    const showDate=dateToStringGmt(item[dataIndex],'monthDate');
                                    cell.innerHTML = `<span>${showDate}</span>`;
                                }
                                if(colName==='结束日期'){
                                    let showDate=new Date(item[dataIndex]);
                                    showDate.setDate(showDate.getDate()-1)                                    
                                    showDate=dateToStringGmt(showDate,'monthDate');
                                    cell.innerHTML = `<span>${showDate}</span>`;
                                    // 检查剩余节数并设置结束日期单元格样式
                                    if (item[4] <= 5) {
                                        cell.innerHTML = `<span style='color:red;font-size:10px;'>${showDate}</span>`;
                                    }
                                    const today=new Date();
                                    let calDate=new Date(item[dataIndex]);
                                    calDate.setDate(calDate.getDate()-1)
                                    const daysDiff=compareDatesOnly2(today,calDate);
                                    if(daysDiff<=5){
                                        cell.innerHTML = `<span style='color:red;font-size:8px;'>${showDate} (剩${daysDiff}天)</span>`;     
                                        if(daysDiff===0){
                                            cell.innerHTML = `<span style='color:red;font-size:8px;'>${showDate} (今天)</span>`;     
                                        }                
                                    }
                                }
                                if(colName==='剩余节数'){
                                    if(item[dataIndex]<=5){
                                        cell.innerHTML = `<span style='color:red;font-size:12px;'>${item[dataIndex]}</span>`;
                                        // 设置结束日期单元格样式
                                        const endDateCell = row.cells[headerOrder.indexOf('结束日期')];
                                        endDateCell.innerHTML = `<span style='color:red;font-size:8px;'>${endDateCell.textContent}</span>`;
                                    }
                                    const today=new Date();
                                    let showDate=new Date(item[6]);
                                    showDate.setDate(showDate.getDate()-1)
                                    const daysDiff=compareDatesOnly2(today,showDate);
                                    if(daysDiff<=5){                         
                                        showDate=dateToStringGmt(showDate,'date');
                                        cell.innerHTML = `<span style='color:red;font-size:12px;'>${item[dataIndex]}</span>`;                    
                                    }

                                }
                                if(colName==='教练'){                                
                                    cell.innerHTML = `${insIdName.slice(8,)}`;                                
                                }
                                if(colName==='返还金额'){
                                    let buyDate=new Date(item[10]);
                                    // console.log('buyDate:',buyDate)
                                    // console.log('compare days:',compareDatesOnly2(buyDate,new Date('2024-06-18')))
                                    //6月18日后购买返500，除非备注中有说明。6月18日前返1000
                                    if(compareDatesOnly2(new Date('2024-06-18'),buyDate)<=0){
                                        cell.innerHTML = `<span>1000</span>`;
                                    }else{
                                        cell.innerHTML = `<span>500</span>`;
                                        let regex = /返\d+/g;
                                        if (regex.test(item[9])) {
                                            back_amount = item[9].match(regex).map(match => match.replace('返', ''));
                                            cell.innerHTML = `<span style="color:orange;">${back_amount}*</span>`;
                                        }
                                    }
                                }

                            }                            
                        }
                        row.classList.add('lmt-15-list');        
                        nOrder+=1;                
                    }
                    
                });

            });

            msgBox.style.display='flex';
            // msgBox.appendChild(title);
            const hr=document.createElement('hr');
            hr.style.width='100%';
            msgBox.appendChild(hr);
            // msgBox.appendChild(title);
            table.classList.add('table-lmt15')
            msgBox.appendChild(table);
            msgBox.classList.add('lmt-15-msgbox-page');    
            titleBox.innerHTML=`新人首单30天15节课程统计<div>（共${nOrder-1}单）</div>`;     
        }
    })
    .catch(error=>{
        console.log(error)
    });
}


function indexMsgAlertAll2(insIdList,divId,divTitle,msgId){
    const lmtDataDiv=document.getElementById(divId);
    const titleBox=document.getElementById(divTitle);
    const msg=document.getElementById(msgId);
   
    // console.log('ins id page:',insIdPage);
    msg.innerHTML='正在获取数据……'
    lmtDataDiv.innerHTML='';
    fetch('./query_lmt_15')
    .then(response=>response.json())
    .then(data=>{
        // console.log('lmt 15 data:',data);
        if(data['res']==='ok'){
            msg.innerHTML='';
            const invalidTxtColor='#e0553d';
            const validTxtColor='#3de06e';
            const itemNameColor='#265666';
            const keyColor='#f56042';
            const today=new Date();
            let n=1;
            titleBox.innerHTML=`新人首单30天15节课程统计<div>（共${data['data_dic'].length}人）</div>`;
            titleBox.style.color='#2f7991';
            // lmtDataDiv.appendChild(titleBox);

            data['data_dic'].forEach(element => {
                // console.log(element);
                const div=document.createElement('div');
                const num=document.createElement('div');
                const backAmtDiv=document.createElement('div');
                
                //姓名及卡号
                num.innerHTML=`${n}`;
                const cusName=document.createElement('div');
                cusName.innerHTML=`<span style='font-size:16px;color:#2f7991;font-weight:bold;'>${element['cus_name']}</span> / <span style='color:#2f7991;'>${element['ins_names']}</span>`;
                const cardId=document.createElement('div');
                cardId.innerHTML=`<span style='color:${itemNameColor};'>卡号：</span>${element['card_id']}`;
                
                //状态
                const status=document.createElement('div');
                const dayDiff=compareDatesOnly2(today,new Date(element['end_time']));
                // console.log(element['卡号'],dayDiff); 
                let statusStr=`剩余 ${element['cls_remain_qty']}节 / ${dayDiff}天`;
                if(element['cls_remain_qty']<=3){
                    statusStr=`剩余 <span style='color:${keyColor};font-weight:bold;'>${element['cls_remain_qty']}节 </span>/ ${dayDiff}天`;
                }
                if(dayDiff<=5){
                    statusStr=`剩余 ${element['cls_remain_qty']}节 /<span style='color:${keyColor};font-weight:bold;'> ${dayDiff}天</span>`;
                }
                if(element['cls_remain_qty']<=3 & dayDiff<=5){
                    statusStr=`剩余 <span style='color:${keyColor};font-weight:bold;'>${element['cls_remain_qty']}节 / ${dayDiff}天</span>`;
                }

                status.innerHTML=`<span style='color:${itemNameColor};'>状态：</span>${statusStr}`;

                //返现金额
                let backAmtStr;
                const buyDate=new Date(dateToStringGmt(element['buy_date'],'date'));
                buyDate.setHours(0,0,0,0);
                if(compareDatesOnly2(new Date('2024-06-18'),buyDate)<=0){
                    backAmtStr = `<span  style="color:orange;font-weight:bold;">1000元</span>`;
                }else{
                    backAmtStr = `<span  style="color:orange;font-weight:bold;">500元</span>`;
                    let regex = /返\d+/g;
                    if (regex.test(element['cmt'])) {
                        backAmtStr = element['cmt'].match(regex).map(match => match.replace('返', ''));
                        backAmtStr = `<span style="color:orange;font-weight:bold;">${backAmtStr}元*</span>`;
                    }
                }
                backAmtDiv.innerHTML=`<span style='color:${itemNameColor};'>返现金额：</span>${backAmtStr}`;

                //有效期
                const prd=document.createElement('div');
                const endDate= new Date(element['end_time']);
                endDate.setHours(0,0,0,0);
                endDate.setDate(endDate.getDate()-1);

                prd.innerHTML=`<span style='color:${itemNameColor};'>有效期：</span>${dateToStringGmt(element['start_time'],'dateDot')} - ${dateToString(endDate,'dateDot')}`;
                
                num.classList.add('num-box');

                div.appendChild(num);
                div.appendChild(cusName);
                div.appendChild(cardId);
                div.appendChild(status);
                div.appendChild(backAmtDiv);
                div.appendChild(prd);

                div.classList.add('inner-box');

                lmtDataDiv.appendChild(num);
                lmtDataDiv.appendChild(div);
                lmtDataDiv.classList.add('outer-box');
                n+=1;
            });


          
        }else{
            lmtDataDiv.innerHTML='';
            msg.innerHTML=`没有数据`;
        }
    })
    .catch(error=>{
        console.log(error)
    });
}

function showActivitySendCls(){
    const actCls=document.getElementById('activitySendInfo');
    actCls.innerHTML='';
    let insIdPage;
    if(insRole==='ins'){
        insIdPage=insId;
    }else{
        //特殊，陆的情况
        if(insRole==='admin'){
            if(insId==='LZADM002' || insId==='LZADM001'){
                insIdPage='LZINS001';
            }
            
        }
    }

    // insIdPage='LZINS005';

    fetch('/get_activity_cls_info', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body:JSON.stringify({"insIdName":insIdPage})
        })
        .then(response => response.json())
        .then(data => {
            // console.log('activity send cls data:',data)
            if(data['res']==='ok'){
                let insActClsList=[];
                Object.values(data['data']).forEach(element => {
                    if(element['ins_ids'].includes(insIdPage)){
                        insActClsList.push(element); 
                    }
                    // console.log('entries:',element);
                });
                // console.log('ins act cls list:',insActClsList);
                //如果教练有赠课会员
                if(insActClsList){
                    let cusArr=[];
                    Object.values(insActClsList).forEach(ele=>{
                        //显示的结束日，不包括当天，显示为前一天。
                        const dateShow=new Date(ele['end_time']);
                        dateShow.setDate(dateShow.getDate()-1);
                        cusArr.push(`${ele['cus_name']} ${parseInt(ele['cls_remain_qty'])}节 | ${dateToString(dateShow,'monthDayDot')}`)
                    });
                    const str=cusArr.join('，');
                    
                    const div=document.createElement('div');
                    div.style.fontSize='12px';
                    div.style.textAlign='center';
                    div.innerHTML=`<div style="background-color:#a18e5a;color:#ffffff;margin-bottom:5px;">会员活动赠课情况</div>`;

                    const actClsInfo=document.createElement('div');
                    actClsInfo.style.color='#8c7430';
                    actClsInfo.style.fontSize='12px';
                    actClsInfo.style.textAlign='center';
                    actClsInfo.innerHTML=`${str}`;

                    actCls.appendChild(div);
                    actCls.appendChild(actClsInfo);


                }else{
                    actCls.innerHTML='';
                }
               
                
            }else{               
                actCls.innerHTML='';
            }

         })
        .catch(error => console.error('Error:', error));




}


function showInsJob(){
    const insJob=document.getElementById('insJobStat');
    insJob.innerHTML='';
    let insIdPage;
    if(insRole==='ins'){
        insIdPage=insId;
    }else{
        //特殊，陆的情况
        if(insRole==='admin'){
            if(insId==='LZADM002' || insId==='LZADM001'){
                insIdPage='LZINS001';
            }
            
        }
    }

    fetch('/get_ins_job_stat', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body:JSON.stringify({"insIdName":insIdPage})
        })
        .then(response => response.json())
        .then(data => {
            console.log('cus buy recs:',data)
            if(data['res']==='ok'){
                const jobData=data['data'];      
                const saleQty=jobData['ins_sale_stat'][0];
                const saleAmt=jobData['ins_sale_stat'][1];
                const trialRateTotal=jobData['trial_dealed_stat'][0][4];
                const insTrialQty=jobData['trial_dealed_stat'][1][2];
                const insTrialQtyDealed=jobData['trial_dealed_stat'][1][3];
                const insTrialRate=jobData['trial_dealed_stat'][1][4];

                const insJobTxt=document.createElement('div');
                insJobTxt.id='insJobTxt';
                insJobTxt.innerHTML=`<div style="font-size:12px;text-align:center;"><p>本月截至今天</p><p>你有 ${saleQty} 单业绩，总金额 ${saleAmt} 元</p><p>体验课 ${insTrialQty} 单，成交 ${insTrialQtyDealed} 单，出单率 ${(insTrialRate*100).toFixed(2)}% </p><p style="color:#dea918;">本店体验课总出单率 ${(trialRateTotal*100).toFixed(2)}%</p></div>`;
                
                const dateBox=document.getElementById('date');
                dateBox.style.marginBottom='2px';
                const hr=document.createElement('hr');
                insJob.appendChild(hr);
                insJob.appendChild(insJobTxt);
                insJob.appendChild(hr);
            }else{               
                insJob.innerHTML='';
            }

         })
        .catch(error => console.error('Error:', error));

}

function showThisMonthDueCusList(){
    const thisMonthDueCusList=document.getElementById('thisMonthDueCusList');
    thisMonthDueCusList.style.width='100%';
    thisMonthDueCusList.innerHTML='';
    let insIdPage;
    if(insRole==='ins'){
        insIdPage=insId;
    }else{
        //特殊，陆的情况
        if(insRole==='admin'){
            if(insId==='LZADM002' || insId==='LZADM001'){
                insIdPage='LZINS001';
            }
            
        }
    }
    fetch('/get_this_month_due_data')
    .then(response=>response.json())
    .then(data=>{
        if(data['res']==='ok'){
            // console.log('due data:',data['data'])
            let count=0;
            const dueData=data['data'];
            let cusStr='';
            dueData.forEach(item=>{   
                if(item[0]===insIdPage){
                    const cusdate=new Date(item[5]);
                    const showDate=new Date(item[5]);
                    showDate.setDate(showDate.getDate()-1)
                    // console.log('showdate:',showDate,'\ntoday:',new Date(),'\ncompare days:',compareDatesOnly(showDate,new Date()));   
                    if(count===0){
                        if(compareDatesOnly2(new Date(),showDate)===0){
                            cusStr+=`<span style="font-weight:bold;color:#cf432d;">${item[3]}(今天)</span>`;
                        }
                        if(compareDatesOnly2(new Date(),showDate)>0){      
                            cusStr+=`${item[3]}(${(showDate.getUTCMonth()+1)}.${showDate.getDate()})`;
                        }      
                        if(compareDatesOnly2(new Date(),showDate)<0){      
                            cusStr+=`<span style="color:#9c9b9a;">${item[3]}(${showDate.getUTCMonth()+1}.${showDate.getDate()})</span>`;
                        }    
                    }else{
                        if(compareDatesOnly2(new Date(),showDate)===0){
                            cusStr+=`<span style="color:#9c9b9a;">，</span><span style="font-weight:bold;color:#cf432d;">${item[3]}(今天)</span>`;
                        }
                        if(compareDatesOnly2(new Date(),showDate)>0){      
                            cusStr+=`<span style="color:#9c9b9a;">，</span>${item[3]}(${(showDate.getUTCMonth()+1)}.${showDate.getDate()})`;
                        }      
                        if(compareDatesOnly2(new Date(),showDate)<0){      
                            cusStr+=`<span style="color:#9c9b9a;">，${item[3]}(${showDate.getUTCMonth()+1}.${showDate.getDate()})</span>`;
                        }    
                    }
                    
                               
                    count+=1;
                }                      
            });
            // cusStr=cusStr.slice(1,);
            const hr=document.createElement('hr');
            const div=document.createElement('div');
            div.style.fontSize='12px';
            div.style.textAlign='center';
            div.innerHTML=`<div style="background-color:#cf432d;color:#ffffff">本月你有下列会员的限时课程到期</div><p style="color:#cf432d;">${cusStr}</p>`;

            // thisMonthDueCusList.appendChild(hr);
            thisMonthDueCusList.appendChild(div);

            if(count===0){
                thisMonthDueCusList.innerHTML='';
            }


        }else{
            thisMonthDueCusList.innerHTML='';
        }
    })
    .catch(error=>console.log(error))
    
}

function showThisMonthBirthdayCus(){
    const birthdayCusList=document.getElementById('birthdayCusList');
    birthdayCusList.style.width='100%';
    birthdayCusList.style.marginBottom='20px';
    birthdayCusList.innerHTML='';

    let insIdPage;
    if(insRole==='ins'){
        insIdPage=insId;
    }else{
        //特殊，陆的情况
        if(insRole==='admin'){
            if(insId==='LZADM002' || insId==='LZADM001'){
                insIdPage='LZINS001';
            }
            
        }
    }


    fetch('/get_cus_birthday')
    .then(response=>response.json())
    .then(data=>{
        if(data['res']==='ok'){
            let count=0;
            const bthData=data['data'];
            // console.log(data['data']);
            let str='';
            bthData.forEach(d=>{
                const bthMonth=new Date(d['birthday']).getUTCMonth();
                const bthDate=new Date(d['birthday']).getUTCDate();
                const today=new Date();
                const thisMonth=today.getMonth();
                if(bthMonth===thisMonth && insIdPage===d['ins_id']){                    
                    if(bthDate===today.getDate()){
                        str+=`<span style="color:#4dbf4e;font-weight:bold;">${d['cus_name']}（今天，${calculateAge(d['birthday'])}岁）</span>，`;
                    }else{
                        str+=`${d['cus_name']}（${bthMonth+1}月${bthDate}日，${calculateAge(d['birthday'])}岁），`;
                    }
                    count+=1;
                }
            });
            str=str.slice(0,-1);
            // console.log(str)

            // const hr=document.createElement('hr');
            const div=document.createElement('div');
            div.style.fontSize='12px';
            div.style.textAlign='center';
            div.innerHTML=`<div style="background-color:#4dbf4e;color:#ffffff;width:100%;margin-top:15px;">你有下列会员生日在本月</div><p style="color:#6bc96c;">${str}</p>`;

            // birthdayCusList.appendChild(hr);
            birthdayCusList.appendChild(div);
            
            if(count===0){
                birthdayCusList.innerHTML='';
            }
            


        }else{
            birthdayCusList.innerHTML='';
        }

    })
    .catch(error=>console.log(error))
}

function calculateAge(birthday) {
    // 将生日字符串转换为 Date 对象
    const birthDate = new Date(birthday);
    const today = new Date();
    
    // 计算年差
    let age = today.getFullYear() - birthDate.getFullYear();
    
    // 检查是否还未过今年的生日
    // const monthDiff = today.getMonth() - birthDate.getMonth();
    // if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    //     age--;
    // }
    
    return age;
}

function getContinueClsRec(cardId){
    const continueBuyClsInfo=document.getElementById('continueBuyClsInfo');
    continueBuyClsInfo.innerHTML='';
    fetch('/get_continue_buy_cls_rec', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body:JSON.stringify({"card_id":cardId})
        })
        .then(response => response.json())
        .then(data => {
            // console.log('cus buy recs:',data)
            if(data['res']==='ok'){
                console.log(data)
                if(data['continue_buy_recent_3_times']==='yes'){
                    const continueBuyList=data['data'];
                    // for(i=0;i<continueBuyList.length;i++){
                    //     if(continueBuyList[i]['card_id']===cardId){
                    //         if(parseInt(continueBuyList[i]['cls_tkn_qty'])>=12){
                    //             continueBuyClsInfo.innerHTML=`<span style='color:red;font-size:11px;'>连续续课情况：该单连续续课3次或3次以上，已上课${continueBuyList[i]['cls_tkn_qty']}节。</span>`;
                    //             break;
                    //         }else{
                    //             continueBuyClsInfo.innerHTML='';
                    //         }
                    //     }
                    // }
                
                    for (const key in continueBuyList) {
                        if (continueBuyList.hasOwnProperty(key)) {
                            const item = continueBuyList[key];
                            if (item['card_id'] === cardId) {
                                if (parseInt(item['cls_tkn_qty']) >= 12) {
                                    continueBuyClsInfo.innerHTML = `<span style='color:red;font-size:11px;'>连续续课情况：该单连续续课3次或3次以上，已上课${item['cls_tkn_qty']}节。</span>`;
                                    break;
                                } else {
                                    continueBuyClsInfo.innerHTML = '';
                                }
                            }
                        }
                    }
                    


                }else{
                    continueBuyClsInfo.innerHTML='';
                }

            }else{         
                      
                console.log(data,'get continue buy data error')
            }

         })
        .catch(error => console.error('Error:', error));
}